package cn.antcore.common.authentication.serialize;

import cn.antcore.common.security.mobile.MobileAuthenticationToken;
import cn.antcore.common.user.AuthUserDetails;
import cn.antcore.common.user.UserGrantedAuthority;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import java.io.IOException;
import java.util.List;

/**
 * 自定义MobileAuthenticationToken反序列化
 * <br>
 * Created by Hong 2024/5/28
**/
public class MobileAuthenticationTokenDeserializer extends JsonDeserializer<MobileAuthenticationToken> {

    @Override
    public MobileAuthenticationToken deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JacksonException {
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode jsonNode = mapper.readTree(jp);
        List<? extends GrantedAuthority> authorities = mapper.convertValue(jsonNode.get("authorities"), new TypeReference<>() {
        });
        WebAuthenticationDetails details = mapper.convertValue(jsonNode.get("details"), WebAuthenticationDetails.class);
        AuthUserDetails principal = mapper.convertValue(jsonNode.get("principal"), AuthUserDetails.class);
        MobileAuthenticationToken token = new MobileAuthenticationToken(principal, authorities);
        token.setDetails(details);
        return token;
    }
}
